import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/api/common_service.dart';

import 'package:wanandroid_flutter/model/article_model.dart';
import 'package:wanandroid_flutter/utils/timeline_util.dart';
import 'package:wanandroid_flutter/utils/router_push_util.dart';
import 'package:wanandroid_flutter/components/public_widget.dart';

class SearchResultPage extends StatefulWidget {
  // String inpValue;
  // SearchResultPage(ValueKey<String> key) : super(key: key) {
  //   this.inpValue = key.value.toString();
  // }
  final inpValue;
  SearchResultPage(this.inpValue);

  /// 这里好像会有bug‘
  /// https://github.com/shijiacheng/wanandroid_flutter/blob/e67b43509222ec4a01172fb32bd7792533aa8a88/lib/ui/SearchResultPageUI.dart

  _SearchResultPageState createState() => _SearchResultPageState();
}

class _SearchResultPageState extends State<SearchResultPage> {
  List<Article> _datas = List();
  ScrollController scrollController = ScrollController();
  int _page;
  bool isAllData = false;
  bool noResult = false;

  @override
  void initState() {
    _getData();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getMore();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  /// =======================================================

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _getData,
      child: ListView.separated(
        padding: const EdgeInsets.all(16.0),
        itemBuilder: _renderRow,
        itemCount: _datas.length > 0 ? _datas.length + 1 : 1,
        controller: scrollController,
        separatorBuilder: (BuildContext context, int index) => Container(
              height: 0.5,
              color: Colors.grey[600],
            ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (noResult) return NoResultWidget();

    if (index < _datas.length) return _itemView(context, index);

    if (!isAllData) return GetMoreWidget();

    return null;
  }

  Widget _itemView(BuildContext context, int index) {
    return GestureDetector(
      child: _newsRow(_datas[index]),
      onTap: () {
        RouterPush.toWebview(context, _datas[index].title, _datas[index].link);
      },
    );
  }

  Widget _newsRow(Article item) {
    return Column(
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 16.0),
          child: Text(
            item.title,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
            textAlign: TextAlign.left,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Container(
          padding: const EdgeInsets.fromLTRB(8, 0, 8, 16.0),
          child: Row(
            children: <Widget>[
              Text(
                item.author,
                style: TextStyle(fontSize: 12, color: Colors.grey),
              ),
              Expanded(
                child: Text(
                  TimelineUtil.format(item.publishTime),
                  style: TextStyle(fontSize: 12.0, color: Colors.grey),
                  textAlign: TextAlign.right,
                ),
              )
            ],
          ),
        ),
      ],
    );
  }

  /// ==================================================
  Future<Null> _getData() async {
    _page = 0;
    String str = widget.inpValue;

    CommonService().getSearchResult((ArticleModel articleModel) {
      setState(() {
        if (articleModel.data.datas.length == 0) {
          noResult = true;
        } else if (articleModel.data.datas.length != 20) {
          isAllData = true;
        }
        _datas = articleModel.data.datas;
      });
    }, _page, str);
  }

  Future<Null> _getMore() async {
    _page++;
    String str = widget.inpValue;

    CommonService().getSearchResult((ArticleModel articleModel) {
      setState(() {
        if (articleModel.data.datas.length != 20) {
          isAllData = true;
        }
        _datas.addAll(articleModel.data.datas);
      });
    }, _page, str);
  }
}
